﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using FineUI;
using SDLITS.Common;
using SDLITS.Model;
using MySoft.Data;
using System.Data;
using System.Data.SqlClient;
namespace SDLITS.Web.Customer
{
    public partial class CompanyChange : CommonBase
    {
        #region 页面初始化
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindArea();
                LoadData();
            }
        }
        #endregion
        protected void BindArea()
        {
            List<Area> lists = SDDbSession.Default.From<Area>().ToList();
            drp_area.DataSource = lists;
            drp_area.DataTextField = "AreaName";
            drp_area.DataValueField = "AreaID";
            drp_area.DataBind();
        }
        #region 读取数据
        private void LoadData()
        {
            int id = 0;
            if (!string.IsNullOrEmpty(Request["id"]))
            {
                id = int.Parse(Request["id"]);
            }
            if (id > 0)
            {
                V_CompanyARU Tm = SDDbSession.Default.From<V_CompanyARU>().Where(V_CompanyARU._.CompanyID == id).ToFirst();
                SqlParameter[] sp = new SqlParameter[]{
                    new SqlParameter("@CompanyID",id),
                    new SqlParameter("@SPAction","SelectLastByCompanyID")
                };
                DataSet ds = SDDbSession.Default.FromProc("TableContract").AddParameter(sp).ToDataSet();
                if (Tm != null)
                {
                    txt_qym.Text = Tm.CompanyName;
                    drp_area.SelectedValue = Tm.AreaID.ToString();
                    BindRoom(Tm.AreaID.ToString());
                    drp_room.SelectedValue = Tm.RoomID.ToString();
                    hidroom.Text = Tm.RoomID.ToString();
                    txt_ywfw.Text = Tm.Business;
                    txt_lxr.Text = Tm.ContactPerson;
                    txt_lxdh.Text = Tm.Phone;
                    txt_fax.Text = Tm.Fax;
                    txt_email.Text = Tm.Email;
                }
                if (ds != null && ds.Tables.Count > 0&&ds.Tables [0].Rows.Count>0)
                {
                    DataRow dr1=ds.Tables[0].Rows[0];
                    hidcontractid.Text = dr1["ContractID"] is DBNull ? "" : dr1["ContractID"].ToString();
                    txt_no.Text = dr1["ContractNo"] is DBNull ? "" : dr1["ContractNo"].ToString();
                    txt_contractor.Text = dr1["Contractor"] is DBNull ? "" : dr1["Contractor"].ToString();
                    txt_phone.Text = dr1["Phone"] is DBNull ? "" : dr1["Phone"].ToString();
                    if (!(dr1["StartDate"] is DBNull))
                    {
                        txt_start.SelectedDate = Convert.ToDateTime(dr1["StartDate"].ToString());
                    }
                    if (!(dr1["EndDate"] is DBNull))
                    {
                        txt_end.SelectedDate = Convert.ToDateTime(dr1["EndDate"].ToString());
                    }
                    txt_comvol.Text = dr1["CompanyCardVol"] is DBNull ? "" : dr1["CompanyCardVol"].ToString();
                    txt_softvol.Text = dr1["SoftCardVol"] is DBNull ? "" : dr1["SoftCardVol"].ToString();
                    txt_note.Text = dr1["Note"] is DBNull ? "" : dr1["Note"].ToString();
                    txt_rent.Text = dr1["Rent"] is DBNull ? "" : dr1["Rent"].ToString();
                    txt_rentmanage.Text = dr1["RentManage"] is DBNull ? "0" : dr1["RentManage"].ToString();
                    if (ds.Tables[2].Rows.Count > 0)
                    {
                        DataRow dr2 = ds.Tables[2].Rows[0];
                        txt_elec.Text = dr2["PreMonthAmount"] is DBNull ? "" : dr2["PreMonthAmount"].ToString();
                    }
                    else
                    {
                        txt_elec.Text = "0";
                    }
                }
                else
                {
                    txt_no.Text = DateTime.Now.ToString("yyyyMMddHHmmss");
                }
            }
            else
            {
                txt_no.Text = DateTime.Now.ToString("yyyyMMddHHmmss");
            }
        }
        #endregion

        #region 保存数据
        
        protected void btnSaveRefresh_Click(object sender, EventArgs e)
        {
            int returnvalue = 0;
            if (!string.IsNullOrEmpty(Request["id"]))
            {
                #region 修改
                if (string.IsNullOrEmpty(drp_room.SelectedValue))
                {
                    Alert.Show("请选择企业所在房间！");
                    return;
                }
                int id = int.Parse(Request["id"]);
                SqlParameter[] sp = new SqlParameter[]{
                    new SqlParameter("@CompanyID",id),
                    new SqlParameter("@CompanyName",txt_qym.Text),
                    new SqlParameter("@RoomID",drp_room.SelectedValue),
                    new SqlParameter("@ContactPerson",txt_lxr.Text),
                    new SqlParameter("@Business",txt_ywfw.Text),
                    new SqlParameter("@Phone",txt_lxdh.Text),
                    new SqlParameter("@Fax",txt_fax.Text),
                    new SqlParameter("@Email",txt_email.Text),
                    new SqlParameter("@SPAction","Update")
                };
                SDDbSession.Default.FromProc("TableCompany").AddParameter(sp).ExecuteNonQuery();

                ModelLoginUser user = Session["LoginUser"] as ModelLoginUser;
                int contractID = string.IsNullOrEmpty(hidcontractid.Text) ? -1 : Convert.ToInt32(hidcontractid.Text);
                SqlParameter[] sp2 = new SqlParameter[]{
                    new SqlParameter("@ContractNo",txt_no.Text),
                    new SqlParameter("@CompanyID",id),
                    new SqlParameter("@StatusID",1),
                    new SqlParameter("@Contractor",txt_contractor.Text),
                    new SqlParameter("@Phone",txt_phone.Text),
                    new SqlParameter("@RoomID",drp_room.SelectedValue),
                    new SqlParameter("@StartDate",txt_start.SelectedDate),
                    new SqlParameter("@EndDate",txt_end.SelectedDate),
                    new SqlParameter("@Rent",txt_rent.Text),
                    new SqlParameter("@CompanyCardVol",txt_comvol.Text),
                    new SqlParameter("@SoftCardVol",txt_softvol.Text),
                    new SqlParameter("@Note",txt_note.Text),
                    new SqlParameter("@CreateUserID",user.UserID),
                    new SqlParameter("@CreateDate",DateTime.Now),
                    new SqlParameter("@RentManage",txt_rentmanage.Text),
                    new SqlParameter("@SPAction","Insert")
                };
                SqlParameter[] sp3 = new SqlParameter[]{
                    new SqlParameter("@ContractID",contractID),
                    new SqlParameter("@ContractNo",txt_no.Text),
                    new SqlParameter("@CompanyID",id),
                    new SqlParameter("@StatusID",1),
                    new SqlParameter("@Contractor",txt_contractor.Text),
                    new SqlParameter("@Phone",txt_phone.Text),
                    new SqlParameter("@RoomID",drp_room.SelectedValue),
                    new SqlParameter("@StartDate",txt_start.SelectedDate),
                    new SqlParameter("@EndDate",txt_end.SelectedDate),
                    new SqlParameter("@Rent",txt_rent.Text),
                    new SqlParameter("@CompanyCardVol",txt_comvol.Text),
                    new SqlParameter("@SoftCardVol",txt_softvol.Text),
                    new SqlParameter("@Note",txt_note.Text),
                    new SqlParameter("@CreateUserID",user.UserID),
                    new SqlParameter("@CreateDate",DateTime.Now),
                    new SqlParameter("@RentManage",txt_rentmanage.Text),
                    new SqlParameter("@SPAction","Update")
                };
                if (contractID == -1)
                {
                    SDDbSession.Default.FromProc("TableContract").AddParameter(sp2).ExecuteNonQuery();
                }
                else
                {
                    SDDbSession.Default.FromProc("TableContract").AddParameter(sp3).ExecuteNonQuery();
                }

                //更新 Room, Expense, Company 等相关信息
                if (!drp_room.SelectedValue.Equals(hidroom.Text))
                {
                    if (!string.IsNullOrEmpty(hidroom.Text))
                    {
                        SDDbSession.Default.Update<Room>(Room._.StatusID, 1, Room._.RoomID == hidroom.Text);
                    }
                    SDDbSession.Default.Update<Room>(Room._.StatusID, 2, Room._.RoomID == drp_room.SelectedValue);
                }
                SDDbSession.Default.FromSql("UPDATE [MemCard] SET [StartDate] = '" + txt_start.Text + "', [ExpireDate] = '" + txt_end.Text + "' WHERE [CompanyID] = " + id).ExecuteNonQuery();
                InitExpense(id, txt_start.SelectedDate, txt_end.SelectedDate, int.Parse(txt_elec.Text), txt_rent.Text);
                PageContext.RegisterStartupScript(ActiveWindow.GetHideRefreshReference());

                returnvalue = 1;
                #endregion
            }
            else
            {
                #region 添加
                if (string.IsNullOrEmpty(drp_room.SelectedValue))
                {
                    Alert.Show("请选择企业所在房间！");
                    return;
                }
                ModelLoginUser user = Session["LoginUser"] as ModelLoginUser;
                SqlParameter[] sp = new SqlParameter[]{
                    new SqlParameter("@CompanyName",txt_qym.Text),
                    new SqlParameter("@RoomID",drp_room.SelectedValue),
                    new SqlParameter("@ContactPerson",txt_lxr.Text),
                    new SqlParameter("@Business",txt_ywfw.Text),
                    new SqlParameter("@Phone",txt_lxdh.Text),
                    new SqlParameter("@Fax",txt_fax.Text),
                    new SqlParameter("@Email",txt_email.Text),
                    new SqlParameter("@StatusID",1),
                    new SqlParameter("@CreateUserID",user.UserID),
                    new SqlParameter("@CreateDate",DateTime.Now),
                    new SqlParameter("@SPAction","Insert")
                };
                int newid = Convert.ToInt32(SDDbSession.Default.FromProc("TableCompany").AddParameter(sp).ToScalar());
                if (newid > 0)
                {
                    SqlParameter[] sp2 = new SqlParameter[]{
                    new SqlParameter("@ContractNo",txt_no.Text),
                    new SqlParameter("@CompanyID",newid),
                    new SqlParameter("@StatusID",1),
                    new SqlParameter("@Contractor",txt_contractor.Text),
                    new SqlParameter("@Phone",txt_phone.Text),
                    new SqlParameter("@RoomID",drp_room.SelectedValue),
                    new SqlParameter("@StartDate",txt_start.SelectedDate),
                    new SqlParameter("@EndDate",txt_end.SelectedDate),
                    new SqlParameter("@Rent",txt_rent.Text),
                    new SqlParameter("@CompanyCardVol",txt_comvol.Text),
                    new SqlParameter("@SoftCardVol",txt_softvol.Text),
                    new SqlParameter("@Note",txt_note.Text),
                    new SqlParameter("@CreateUserID",user.UserID),
                    new SqlParameter("@CreateDate",DateTime.Now),
                    new SqlParameter("@RentManage",txt_rentmanage.Text),
                    new SqlParameter("@SPAction","Insert")
                    };
                    returnvalue = Convert.ToInt32(SDDbSession.Default.FromProc("TableContract").AddParameter(sp2).ToScalar());

                    hidcontractid.Text = returnvalue.ToString();
                    if (returnvalue > 0)
                    {
                        SDDbSession.Default.FromSql("Update [Company] Set StatusID=1,RoomID=(select top 1 ct.RoomID from [Contract] ct where ct.CompanyID=" + newid + " order by ct.CreateDate Desc) Where CompanyID=" + newid).ExecuteNonQuery();
                        SDDbSession.Default.FromSql("UPDATE [MemCard] SET [StartDate] = '" + txt_start.Text + "', [ExpireDate] = '" + txt_end.Text + "' WHERE [CompanyID] = " + newid).ExecuteNonQuery();
                        InitExpense(newid, txt_start.SelectedDate, txt_end.SelectedDate, int.Parse(txt_elec.Text), txt_rent.Text);
                        PageContext.RegisterStartupScript(ActiveWindow.GetHideRefreshReference());
                    }
                }
                #endregion
            }
            if (returnvalue > 0)
            {
                PageContext.RegisterStartupScript(ActiveWindow.GetHideRefreshReference());
            }
        }
        #endregion
        protected void TextBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindRoom(drp_area.SelectedValue);
        }
        protected void BindRoom(string aid)
        {
            List<Room> list = SDDbSession.Default.From<Room>().Where(Room._.AreaID == aid).ToList();
            drp_room.DataSource = list;
            drp_room.DataTextField = "RoomName";
            drp_room.DataValueField = "RoomID";
            drp_room.DataBind();
        }
        private void SetRoomRent()
        {
            Room room = SDDbSession.Default.From<Room>().Where(Room._.RoomID == drp_room.SelectedValue).ToFirst();
            if (room != null)
            {
                if (room.RentalPrice!=null&&!string.IsNullOrEmpty(room.RentalPrice.ToString()))
                {
                    txt_rent.Text = (Convert.ToDecimal(room.RentalPrice)).ToString();
                    return;
                }
            }
            txt_rent.Text = "0";
        }

        protected void drp_room_SelectedIndexChanged(object sender, EventArgs e)
        {
            SetRoomRent();
        }

        public void InitExpense(int companyID, DateTime? startDate, DateTime? endDate, int preMonthAmoun, string rent)
        {
            decimal rentPrice = 0;
            if (!string.IsNullOrEmpty(rent))
            {
                rentPrice = Convert.ToDecimal(rent);
            }
            SDDbSession.Default.FromSql("delete from expense where companyid=" + companyID).ExecuteNonQuery();
            do
            {
                if (startDate != null && endDate != null)
                {
                    Expense exp = new Expense();
                    exp.DeAttach();
                    exp.ExpenseTypeID = 2;
                    exp.CompanyID = companyID;
                    exp.ExpenseYear = startDate.Value.Year;
                    exp.ExpenseMonth = startDate.Value.Month;
                    exp.PreMonthAmount = preMonthAmoun;
                    exp.SinglePrice = rentPrice;
                    exp.SinglePrice = SDDbSession.Default.From<MasterDic>().ToFirst().ElecPrice;
                    exp.StatusID = 2;
                    SDDbSession.Default.Insert<Expense>(exp);

                    startDate = startDate.Value.AddMonths(1);
                    preMonthAmoun = 0;
                }
            } while (startDate < endDate);
        }
    }
}